import vue from "@vitejs/plugin-vue";
// import VueDevTools from "vite-plugin-vue-devtools";
import vueSetupExtend from "unplugin-vue-setup-extend-plus/vite";
import removeConsole from "vite-plugin-remove-console";
import { viteMockServe } from "vite-plugin-mock";
import { resolve } from "path";
import { defineConfig, loadEnv, ConfigEnv } from "vite";

const pathResolve = (dir: string) => {
	return resolve(__dirname, ".", dir);
};

const alias: Record<string, string> = {
	"/@": pathResolve("./src/"),
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		plugins: [
			// VueDevTools(),
			vue(),
			vueSetupExtend({}),
			removeConsole({ includes: ["log", "warn", "info"] }), // 生产环境移除 console
			viteMockServe({
				mockPath: "mock", // 解析根目录下的 mock 文件夹
				localEnabled: mode.command === "serve", // 开发打包开关
				prodEnabled: mode.command !== "serve" && JSON.parse(env.VITE_PROD_MOCK), // 生产打包开关
				supportTs: false, // 打开后，可以读取 ts 文件模块，但是将无法监视 .js 文件
				injectCode: `
					import { setupProdMockServer } from '../mock/_MockProdServer';
					setupProdMockServer();
				`, // 如果 prodEnabled=true 则该代码会被注入到 injectFile 对应的文件（默认 /src/main.ts）的底部
			}),
		],
		root: process.cwd(),
		resolve: { alias },
		base: mode.command === "serve" ? "./" : env.VITE_PUBLIC_PATH,
		server: {
			host: "0.0.0.0",
			port: env.VITE_PORT as unknown as number,
			open: JSON.parse(env.VITE_OPEN),
			hmr: true,
			// 自定义代理规则
			// proxy: {
			// 	"/gitee": {
			// 		target: "https://gitee.com",
			// 		ws: true,
			// 		changeOrigin: true,
			// 		rewrite: path => path.replace(/^\/gitee/, ""),
			// 	},
			// },
		},
		build: {
			outDir: "dist",
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
					manualChunks(id) {
						if (id.includes("node_modules")) {
							return id.toString().split("node_modules/")[1].split("/")[0].toString();
						}
					},
				},
			},
		},
		css: { preprocessorOptions: { css: { charset: false } } },
		define: {
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__PROJ_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
